<template>
  <content-field>
    <n-card>
      <template #header>最近文章</template>
      <n-grid :cols="4">
        <n-gi :span="1">
          <n-statistic label="总计文章" :value="count">
            <template #prefix> </template>
            <template #suffix>篇</template>
          </n-statistic>
        </n-gi>
      </n-grid>
    </n-card>
    <br />

    <n-card class="background">
      <template #header>-</template>
      <template #header-extra>
        <n-pagination
          v-model:page="page"
          :page-count="Math.ceil(count / 10)"
          show-quick-jumper
        >
          <template #goto> 跳转至 </template>
        </n-pagination>
      </template>

      <n-grid :cols="2" :x-gap="12" :y-gap="8">
        <n-gi :span="2" v-for="article of articlelist" :key="article.id">
          <article-card :article="article" />
        </n-gi>
      </n-grid>
      <template #footer>
        <n-space justify="end"
          ><n-pagination
            v-model:page="page"
            :page-count="Math.ceil(count / 10)"
            show-quick-jumper
          >
            <template #goto> 跳转至 </template>
          </n-pagination></n-space
        >
      </template>
    </n-card>
  </content-field>
</template>

<script>
import ContentField from "@/components/ContentField.vue";
import { ref } from "@vue/reactivity";
import ArticleCard from "@/components/cards/ArticleCard.vue";
import { watch } from "@vue/runtime-core";
import remoteData from "@/composables/RemoteData";
import { useMessage } from "naive-ui";

export default {
  components: { ContentField, ArticleCard },
  setup() {
    // 向给定ID的用户发起请求
    let articlelist = ref([]);
    let count = ref(0);
    let page = ref(1);
    const message = useMessage();
    const { get_articles } = remoteData();
    /**
     * 初始请求第一页
     */
    get_articles(1, articlelist, count).catch((error) => {
      message.error(error.data.detail);
    });

    /**
     * page变化，请求新的页
     */
    watch(page, (newpage) => {
      get_articles(newpage, articlelist, count).catch((error) => {
        message.error(error.data.detail);
      });
    });
    return {
      get_articles,
      articlelist,
      count,
      page,
    };
  },
};
</script>

<style scoped>
/* .background {
  background-color: #f7f7f7;
} */
</style>